package com.kingyea.mobilepolice.security;

import com.alibaba.fastjson.JSON;
import com.kingyea.mobilepolice.permission.service.PermissionService;
import com.kingyea.mobilepolice.redis.service.RedisService;
import com.kingyea.mobilepolice.role.service.RoleService;
import com.kingyea.mobilepolice.system.StateCode;
import com.kingyea.mobilepolice.user.bean.User;
import com.kingyea.mobilepolice.user.service.UserService;
import com.kingyea.mobilepolice.util.ExceptionConditions;
import com.kingyea.mobilepolice.util.GlobalVar;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 提供自定义用户信息获取服务
 * Created by wangyunfei on 2017/6/9.
 */
//@Service("userDetailsService")
//@Slf4j
@Component
public class DomainUserDetailsService implements UserDetailsService {

   /* @Autowired
    private  SysUserRepository sysUserRepository;*/

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private PermissionService permissionService;

    @Autowired
    private RedisService redisService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        /*String lowcaseUsername = username.toLowerCase();
        Optional<SysUser> realUser = sysUserRepository.findOneWithRolesByUsername(lowcaseUsername);*/

        User user = userService.getByUserName(username);
        ExceptionConditions.checkNotNull(user, StateCode.USER_NOT_FOUND_ERROR);
//        List<Role> roleList = roleService.searchByUserId(user.getId());
//        PermissionCondition permissionCondition = new PermissionCondition();
//        permissionService.search(permissionCondition);
//        roleList.stream().map(role -> new SimpleGrantedAuthority(role.getRoleName())).collect(Collectors.toCollection(HashSet<GrantedAuthority>::new));

//        user.doSecurityUser(permissionService.allRoleAndPermissionByUserId(user.getId()));
        User userCahce = new User(user, permissionService.allRoleAndPermissionByUserId(user.getUserId()));

        // 加入 redis ： key:LoginId val:User


        String key = new String(GlobalVar.user_prefix + user.getLoginId().trim());
        System.out.println(key);
        String val = (JSON.toJSONString(dofilter(userCahce, new ArrayList<String>() {{
            add("password");
        }})));
        System.out.println(val);
        redisService.set(null, key.getBytes(), val.getBytes());


        return new org.springframework.security.core.userdetails.User(user.getLoginId(), user.getPassword(), permissionService.allRoleAndPermissionByUserId(user.getUserId()));
//        return userCahce;
        /*return realUser.map(user -> {
            Set<GrantedAuthority> grantedAuthorities = user.getAuthorities();
            return new User(user.getUsername(),user.getPassword(),grantedAuthorities);
        }).orElseThrow(() -> new UsernameNotFoundException("用户" + lowcaseUsername + "不存在!"));*/
    }


    /**
     * 关键字过滤
     */
    private Object dofilter(Object obj, List<String> keyword) {
        String s = JSON.toJSONString(obj);
        // 尝试map
        List l = null;
        Map m = null;
        try {
            m = JSON.parseObject(s, Map.class);
        } catch (Throwable e) {
            //尝试list
            try {
                l = JSON.parseObject(s, List.class);
            } catch (Throwable e1) {
                return null;
            }
        }
        if (m != null) {
            for (Object mapKey : m.keySet()) {
//                String tmp = m.get(mapKey).toString();
                for (String word : keyword) {
                    if (word.equalsIgnoreCase(mapKey.toString())) {
                        m.put(mapKey, "*");
                        continue;
                    }
//                    tmp = tmp.replace(word,"*");
                }
//                m.put(mapKey,tmp);
                dofilter(m.get(mapKey), keyword);
            }
            return m;
        } else {
            List res = new ArrayList();
            for (int i = 0, len = l.size(); i < len; i++) {
                Object o = dofilter(l.get(i), keyword);
                res.add(o);
            }
            return res;
        }
    }
}
